package com.tian.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tian.client.AuthClient;
import com.tian.common.CommonResult;
import com.tian.enums.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.util.List;

/**
 * {@code @description:} 用户认证 获取token 以及token验证
 *
 * @author tianwc 公众号：Java后端技术全栈
 * 在线刷题 1200+java面试题和1000+篇技术文章：<a href="https://woaijava.cc/">博客地址</a>
 * {@code @date:} 2024-04-07 23:07
 * {@code @version:} 1.0
 */
@Slf4j
@PropertySource(value = "classpath:login-filter.properties")
@Component
public class AuthLoginGlobalFilter implements GlobalFilter, Ordered {

    //不需要登录校验的请求路径
    @Value("#{'${ignoreLoginUrls}'.split(',')}")
    private List<String> ignoreLoginUrls;

    @Resource
    private AuthClient authClient;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String uri = request.getURI().getPath();

        //不需要登录校验的请求路径,俗称白名单
        if (ignoreLoginUrls != null && ignoreLoginUrls.contains(uri)) {
            return chain.filter(exchange);
        }
        //获取token
        String accessToken = request.getHeaders().getFirst("Authorization");
        //判断token是否为空
        if (StringUtils.isBlank(accessToken)) {
            return onError(exchange, "尚未登录");
        }
        //校验token
        CommonResult<String> result = authClient.validToken(accessToken);
        if (result.getCode() == ResultCode.SUCCESS.getCode()) {
            ServerHttpRequest shr = request.mutate().header("Authorization", accessToken).build();
            return chain.filter(exchange.mutate().request(shr).build());
        }
        return onError(exchange, result.getMessage());
    }

    private Mono<Void> onError(ServerWebExchange exchange, String msg) {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        ObjectMapper objectMapper = new ObjectMapper();
        String rs = "";
        try {
            rs = objectMapper.writeValueAsString(CommonResult.failed(HttpStatus.UNAUTHORIZED.value(), msg));
        } catch (JsonProcessingException e) {
            log.error("occur Exception:" + e);
        }
        DataBuffer buffer = response.bufferFactory().wrap(rs.getBytes());
        return response.writeWith(Flux.just(buffer));
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
